package com.jichangxiu.framework.advice;

import com.jichangxiu.common.constant.Constant;
import com.jichangxiu.common.entity.bo.Result;
import com.jichangxiu.common.utils.ServletUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * ResponseAdvice:
 *
 * @author Jcx
 * @create 2023-04-04 10:20
 */
@Slf4j
@RestControllerAdvice
@RequiredArgsConstructor
public class ResponseAdvice implements ResponseBodyAdvice<Object> {

    private static final String X_RESPONSE_TIME_HEADER = "X-Response-Time";
    private static final ThreadLocal<Long> startTimeThreadLocal = new ThreadLocal<>();

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (servletRequestAttributes != null) {
            HttpServletRequest request = servletRequestAttributes.getRequest();
            // 如果是自定义注解的请求则对返回内容进行包装，返回固定格式的内容
            String attribute = (String) request.getAttribute(Constant.CUSTOM_MAPPING_ADD_ATTRIBUTE);
            return Constant.CUSTOM_MAPPING_ADD_ATTRIBUTE.equals(attribute);
        }
        return false;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        long startTime = (long) ServletUtils.getRequest().getAttribute("startTime");
        Object result = Result.toResult(body);
        log.warn("请求 " + ServletUtils.getRequest().getRequestURI() + " 一共耗时：" + (System.nanoTime() - startTime) / 1000000.0);
        ServletUtils.getResponse().addHeader(X_RESPONSE_TIME_HEADER, (System.nanoTime() - startTime) / 1000000.0 + "ms");
        return result;
    }

}
